package com.leyou.trade.service.impl;

import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.carts;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartRepository cartRepository;
    /**todo
     * 添加购物车
     */
    @Override
    @Transactional
    public void addCarts(carts carts) {
    //先查验是否已经存在，存在修改数量，不存在直接插入
        //获取用户的id
        Long userId = UserContext.getUser().getId();
        String id = createId(carts.getSkuId());
        //根据id查询
        Optional<carts> optionalCarts = cartRepository.findById(id);
        //如果查到有就修改数量
        if(optionalCarts.isPresent()){
        carts mongoCart = optionalCarts.get();
        mongoCart.setNum(carts.getNum()+mongoCart.getNum());
        mongoCart.setUpdateDate(new Date());
        cartRepository.save(mongoCart);
        }else {
        //不存在，新增
            carts.setId(id);
            carts.setUserId(userId);
            carts.setUpdateDate(new Date());
            cartRepository.save(carts);
        }

    }
    public String createId(long skuId) {
        //拼接用户id和商品id作为联合主键
     return String.format("u%ds%d",UserContext.getUser().getId(),skuId);
    }
    /**todo
     * 查询
     */
    @Override
    public List<carts> listCarts() {
        Long userId = UserContext.getUser().getId();
       List<carts> carts =  cartRepository.findByUserId(userId);
        return carts;
    }

    /**todo
     * 删除购物车
     * @param skuId
     */
    @Override
    public void deletaCart(Long skuId) {
        String id = createId(skuId);
        cartRepository.deleteById(id);
    }
}
